<template>
  <el-form
    label-width="100px"
    ref="skuFormRef"
    :model="skuInfo"
    :rules="skuRules"
  >
    <!-- SPU名称 -->
    <el-form-item label="SPU名称">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <!-- SKU名称 -->
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName" />
    </el-form-item>
    <!-- 价格(元) -->
    <el-form-item label="价格(元)" prop="price">
      <el-input-number
        v-model="skuInfo.price"
        style="width: 100%"
        class="mx-4"
        :min="1"
        :max="10"
        controls-position="right"
      />
    </el-form-item>
    <!-- 重量(千克) -->
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        style="width: 100%"
        class="mx-4"
        :min="1"
        :max="10"
        controls-position="right"
      />
    </el-form-item>
    <!-- 规格描述 -->
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" rows="4" v-model="skuInfo.skuDesc" />
    </el-form-item>
    <!-- 平台属性 -->
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(attr, index) in attrList"
          :key="attr.id"
          :xs="24"
          :sm="12"
          :md="12"
          :lg="8"
        >
          <el-form-item :label="attr.attrName">
            <el-select
              placeholder="请选择"
              v-model="skuInfo.skuAttrValueList[index]"
            >
              <el-option
                v-for="attrValue in attr.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                @click="clearAttrRules"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <!-- 销售属性 -->
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col
          v-for="(saleAttr, index) in spuSaleAttrList"
          :key="saleAttr.id"
          :xs="24"
          :sm="12"
          :md="12"
          :lg="12"
        >
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select
              placeholder="请选择"
              v-model="skuInfo.skuSaleAttrValueList[index]"
            >
              <el-option
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
                :label="saleAttrValue.saleAttrValueName"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                @click="clearSaleAttrRules"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <!-- 图片列表 -->
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        border
        :data="spuImageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <img
              :src="row.imgUrl"
              alt="row.imgUrl"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="名称"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              v-if="row.isDefault === '0'"
              type="primary"
              @click="setDefaultImg(row)"
              >设为默认项</el-button
            >
            <el-button v-else type="success">默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="skuSubmitForm(skuFormRef)"
        >保存</el-button
      >
      <el-button @click="emits('changeScene', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "SkuForm",
}
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue"

import { ElMessage } from "element-plus"

import type { FormInstance, FormRules } from "element-plus"
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from "@/api/product/spu.ts"
import { reqGetAttrInfoList } from "@/api/product/attr.ts"
import { reqSaveSkuInfo } from "@/api/product/sku.ts"
import { useCategoryListStore } from "@/stores/categoryList"
const emits = defineEmits(["changeScene"])
const categoryStore = useCategoryListStore()
const props = defineProps(["currentSpuInfo"])
// 定义储存 平台、销售属性 图片的变量
const attrList = ref([])
const spuSaleAttrList = ref([])
const spuImageList = ref([])

const skuInfo = reactive({
  // spu名称
  skuName: "",
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: "",
  // 默认图片
  skuDefaultImg: "",
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: [],
})

// 书写一个图片的自定义校验规则
const skuImageListValidate = (rule: any, value: any, callback: any) => {
  // console.log(rule, value, callback)
  if (value.length === 0) return callback(new Error("请至少选择一项"))

  if (!value.find(item => item.isDefault === "1"))
    return callback(new Error("请选择默认图片"))
  skuFormRef.value?.clearValidate(["skuImageList"])
  // 什么参数都不写，表示放行
  return callback()
}

// 表单验证需要的变量
const skuFormRef = ref<FormInstance>()
const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: "请输入sku名称", trigger: "blur" },
    { min: 1, max: 10, message: "长度在1到10之间", trigger: "blur" },
  ],
  price: [{ required: true, message: "请输入sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入sku描述", trigger: "blur" }],
  skuAttrValueList: [
    // 平台属性校验规则
    {
      required: true,
      message: "请至少选择一个平台属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuSaleAttrValueList: [
    // 销售属性校验规则
    {
      required: true,
      message: "请至少选择一个销售属性",
      type: "array",
      trigger: "change",
    },
  ],
  skuImageList: [
    // 图片校验规则
    {
      required: true,
      validator: skuImageListValidate,
      trigger: "change",
    },
  ],
})

// 1.获取数据
onMounted(async () => {
  const id = props.currentSpuInfo.id
  const [resAttrList, resSpuSaleAttrList, resSpuImageList] =
    await Promise.allSettled([
      reqGetAttrInfoList(categoryStore),
      reqGetSpuSaleAttrList(id),
      reqGetSpuImageList(id),
    ])
  console.log(resAttrList, resSpuSaleAttrList, spuImageList)
  if (resSpuImageList?.status === "fulfilled")
    spuImageList.value = resSpuImageList.value.map(item => ({
      ...item,
      isDefault: "0",
    }))
  if (resSpuSaleAttrList?.status === "fulfilled")
    spuSaleAttrList.value = resSpuSaleAttrList.value
  if (resAttrList?.status === "fulfilled") attrList.value = resAttrList.value
})

// 2.设置默认图片
const setDefaultImg = row => {
  spuImageList.value.forEach(item => (item.isDefault = "0"))
  row.isDefault = "1"
  skuInfo.skuDefaultImg = row.imgUrl
}

// 3. 当选择图片的时候
const handleSelectionChange = val => {
  skuInfo.skuImageList = val
}

// 4.保存提交数据  表单验证
const skuSubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      skuInfo.spuId = props.currentSpuInfo.id
      skuInfo.category3Id = props.currentSpuInfo.category3Id

      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList
        .filter(Boolean)
        .map(item => {
          const [attrId, attrName, valueId, valueName] = item.split(":")
          return {
            attrId,
            attrName,
            valueId,
            valueName,
          }
        })

      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList
        .filter(Boolean)
        .map(item => {
          const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
            item.split(":")
          return {
            saleAttrId,
            saleAttrName,
            saleAttrValueId,
            saleAttrValueName,
          }
        })
      console.log(skuInfo)

      await reqSaveSkuInfo(skuInfo)

      ElMessage.success("添加sku数据成功...")
      emits("changeScene", 1)
    } else {
      console.log("error submit!", fields)
    }
  })
}

// 5. 清空平台属性的校验规则
const clearAttrRules = () => {
  skuFormRef.value?.clearValidate(["skuAttrValueList"])
}

// 6. 清空销售属性的校验规则
const clearSaleAttrRules = () => {
  skuFormRef.value?.clearValidate(["skuSaleAttrValueList"])
}
</script>

<style></style>
